package com.tensin.mall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.tensin.common.contant.ProductConstant;
import com.tensin.common.to.SkuHasStockTo;
import com.tensin.common.to.SkuReductionTo;
import com.tensin.common.to.SpuBoundTo;
import com.tensin.common.to.es.SkuEsModel;
import com.tensin.common.utils.R;
import com.tensin.mall.product.entity.*;
import com.tensin.mall.product.feign.CouponFeignService;
import com.tensin.mall.product.feign.SearchFeignService;
import com.tensin.mall.product.feign.WareFeignService;
import com.tensin.mall.product.service.*;
import com.tensin.mall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tensin.common.utils.PageUtils;
import com.tensin.common.utils.Query;

import com.tensin.mall.product.dao.SpuInfoDao;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService imagesService;

    @Autowired
    AttrService attrService;

    @Autowired
    ProductAttrValueService attrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存 商品维护-发布商品-保存商品信息
     * TODO 高级篇完善
     * @param vo
     */
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1.保存spu基本信息 pms_spu_info
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(infoEntity);
        
        //2.保存spu描述图片 pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(infoEntity.getId());
        descEntity.setDecript(String.join(",",decript)); //以逗号为非分隔符，把取出的list图片地址描述都拼起来
        spuInfoDescService.saveSpuInfoDesc(descEntity);

        //3.保存spu图片集 pms_spu_images
        List<String> images = vo.getImages();
        imagesService.saveImages(infoEntity.getId(),images);

        //4.保存spu规格参数 pms_produce_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            AttrEntity id = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(id.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(infoEntity.getId());

            return valueEntity;
        }).collect(Collectors.toList());

        attrValueService.saveProductAttr(collect);


        //5.保存spu积分信息 sms数据库 -> sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(infoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0){
            log.error("远程保存spu积分信息失败");
        }



        //6.保存当前spu对应的sku的值

        List<Skus> skus = vo.getSkus();
        if (skus != null && skus.size() > 0){
            skus.forEach(item ->{
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1){
                        defaultImg = image.getImgUrl();
                    }
                }

                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(infoEntity.getBrandId());
                skuInfoEntity.setCatalogId(infoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(infoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                //6.1 sku基本信息 pms_sku_info
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();//自增主键

                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    //没有图片路径的无需保存
                    //返回true就是需要，false就是剔除
                    return StringUtils.hasText(entity.getImgUrl());
                }).collect(Collectors.toList());

                //6.2 sku图片信息 pms_sku_images
                skuImagesService.saveBatch(imagesEntities);



                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);

                    return attrValueEntity;
                }).collect(Collectors.toList());
                //6.3 sku销售属性信息 pms_sku_sale_attr_value
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                //6.4 sku满减、优惠信息
                // sms数据库 -> sms_sku_ladder、sms_sku_full_reduction、sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0"))==1){
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0){
                        log.error("远程保存sku优惠信息失败");
                    }
                }

            });
        }

    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity infoEntity) {
        this.baseMapper.insert(infoEntity);
    }

//    商品维护-spu管理条件查询
    @Override
    public PageUtils queryPageByConditions(Map<String, Object> params) {

        LambdaQueryWrapper<SpuInfoEntity> wrapper = new LambdaQueryWrapper<>();

        /* 前端数据携带-spu管理
        status: 1
        key:
        brandId: 7
        catelogId: 225
         */

        //检索框key部分
        String key = (String) params.get("key");
        if (StringUtils.hasText(key)){
            wrapper.and(w -> w.eq(SpuInfoEntity::getId,key).or().like(SpuInfoEntity::getSpuName,key));
        }
//        if (StringUtils.hasText(key)){
//            wrapper.and(new Consumer<LambdaQueryWrapper<SpuInfoEntity>>() {
//                @Override
//                public void accept(LambdaQueryWrapper<SpuInfoEntity> w) {
//                    w.eq(SpuInfoEntity::getId,key).or().like(SpuInfoEntity::getSpuName,key);
//                }
//            });
//        }

        //检索框status部分
        String status = (String) params.get("status");
        if (StringUtils.hasText(status)){
            wrapper.eq(SpuInfoEntity::getPublishStatus,status);
        }

        //检索框brandId部分
        String brandId = (String) params.get("brandId");
        if (StringUtils.hasText(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq(SpuInfoEntity::getBrandId,brandId);
        }

        //检索框catelogId部分
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.hasText(catelogId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq(SpuInfoEntity::getCatalogId,catelogId);
        }


        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }


    //商品上架
    @Override
    public void up(Long spuId) {


        //1.查出当前spu id对应的所有sku信息、品牌的名称
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);

        //4.查出当前sku的所有规格属性attrs。因为所有的sku的attrs都是一样的，因为是同一个spu，所以查一遍就行，提到外面来查。需要查出search属性为可检索的
        //4.1先查出所有的属性
        List<ProductAttrValueEntity> baseAttrs = attrValueService.baseAttrlistforspu(spuId);
        //4.2过滤掉不可检索的，只留下可检索的
        List<Long> baseAttrIds = baseAttrs.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        //过滤后都是可以被检索的的attrIds（即search的值为1）
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(baseAttrIds);
//        Set<Long> idSet = new HashSet<Long>(searchAttrIds);
        //检测查出的attr是不是在可检索的searchAttrIds里
        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> {
            return searchAttrIds.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());


        //TODO 1.发起远程调用，查看是否还有库存 hasStock


        //拿到所有需要查找是否有库存的id集合
        List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Boolean> stockMap = null;
        //异常捕获，防止网络波动造成的调用失败，导致后面的代码都不执行。
        try{
            R r = wareFeignService.getSkusHasStock(skuIdList);
            //使用里面的数据
            TypeReference<List<SkuHasStockTo>> typeReference = new TypeReference<List<SkuHasStockTo>>() {
            };
            List<SkuHasStockTo> data = r.getData(typeReference);
            stockMap = data.stream().collect(Collectors.toMap(SkuHasStockTo::getId, item -> item.isHasStock()));

        }catch (Exception e){
            log.error("库存查询服务异常：原因{}", e);
        }

        //2.封装信息，封装成es需要搜索使用的字段，即SkuEsModel
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upProducts = skus.stream().map(sku -> {
            //组装需要的数据
            SkuEsModel skuEsModel = new SkuEsModel();

            BeanUtils.copyProperties(sku,skuEsModel);

            //不同的属性进行手动设置 Price Img
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());

            //设置是库存信息
            if (finalStockMap == null){
                skuEsModel.setHasStock(true);
            }else {
                skuEsModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }


            //TODO 2.热度评分，刚上架的默认是0，剩下的根据情况调整
            skuEsModel.setHotScore(0L);

            //TODO 3.查询品牌 和分类的名称
            BrandEntity brand = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(brand.getName());
            skuEsModel.setBrandImg(brand.getLogo());

            CategoryEntity category = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(category.getName());

            //设置检索出来的attrs属性
            skuEsModel.setAttrs(attrsList);



            return skuEsModel;

        }).collect(Collectors.toList());

        //TODO 将数据发送给es进行保存 mall-search
         R r =  searchFeignService.productStatusUp(upProducts);

         if (r.getCode() == 0){
             //远程调用成功
             //TODO 改变商品发布状态的spu

             for (SkuEsModel upProduct : upProducts) {
                 LambdaQueryWrapper<SpuInfoEntity> wrapper = new LambdaQueryWrapper<>();
                 wrapper.eq(SpuInfoEntity::getId, upProduct.getSpuId());
                 SpuInfoEntity entity = this.getOne(wrapper);
                 entity.setPublishStatus(ProductConstant.StatusEnum.SPU_UP.getCode());
                 entity.setUpdateTime(new Date());
                 this.updateById(entity);
             }

         } else {

         }

    }


}